<?php

namespace app\http\middleware;

use app\common\service\Customer;

class FilterWechatLogin {

    public function handle($request, \Closure $next) {

        //跨域处理
        header("Access-Control-Allow-Origin:*");
        header('Access-Control-Allow-Headers: X-Requested-With,SIGN,api-version');

        //判断请求方式
        if(request()->method() != "POST") {
            return errorReturn("errorWechat.errorMethod");
        }

        //数据校验
        $validate = validate("WechatValidate");

        if(false === $validate->scene($request->action(true))
                ->check($request->param())) {
            return errorReturn("errorWechat.errorDataFormat", $validate->getError());
        }

        $token = $request->post('token');

        //判断此路由是否可不验证openid
        $accessRoute = config('constants.wechatAccessRoute');

        if (!in_array($request->action(true), $accessRoute)) {

            // 判断是否传token
            if (isNullOrEmpty($token)) {
                return errorReturn('errorWechat.errorToken');
            }

            // 获取 customer 实体
            $customerService = new Customer();
            $customer = $customerService->findByToken($token);

            // 判断 customer 实体是否存在
            if (isNullOrEmpty($customer)) {
                return errorReturn('errorWechat.errorToken');
            }

            $request->currentCustomer = $customer;

        }

        return $next($request);
    }

}
